package com.interview.rtc.aigc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.interview.rtc.aigc.common.ErrorCode;
import com.interview.rtc.aigc.dao.ChatMessageDao;
import com.interview.rtc.aigc.dao.SessionHistoryDao;
import com.interview.rtc.aigc.dao.UserDao;
import com.interview.rtc.aigc.dto.ChatMessageDto;
import com.interview.rtc.aigc.mapper.ChatMessageMapper;
import com.interview.rtc.aigc.mapper.SessionHistoryMapper;
import com.interview.rtc.aigc.service.SessionHistoryService;
import com.interview.rtc.aigc.utils.ExceptionUtil;
import com.interview.rtc.aigc.vo.MessageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class SessionHistoryServiceImpl implements SessionHistoryService {

    @Autowired
    private SessionHistoryMapper sessionHistoryMapper;

    @Autowired
    private ChatMessageMapper chatMessageMapper;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    @Transactional
    public SessionHistoryDao createSession(SessionHistoryDao sessionHistory) {
        // 参数校验
        ExceptionUtil.assertNotNull(sessionHistory, "会话历史不能为空");
        ExceptionUtil.assertNotNull(sessionHistory.getUserId(), "用户ID不能为空");
        ExceptionUtil.assertTrue(StringUtils.hasText(sessionHistory.getTitle()), "会话标题不能为空");

        // 如果没有提供roomId，生成一个随机的UUID作为roomId
        if (!StringUtils.hasText(sessionHistory.getRoomId())) {
            // 生成一个UUID并从中取出8位字符作为随机字符串，并转换为大写
            String randomPart = UUID.randomUUID().toString().replace("-", "").substring(0, 8).toUpperCase();
            // 组装roomId，格式为"Room-"加8位随机字符串
            String roomId = "Room-" + randomPart;
            sessionHistory.setRoomId(roomId);
        }

        // 设置创建时间和更新时间
        Date now = new Date();
        sessionHistory.setCreateTime(now);
        sessionHistory.setUpdateTime(now);

        try {
            // 保存会话历史
            sessionHistoryMapper.insert(sessionHistory);
            return sessionHistory;
        } catch (Exception e) {
            // 处理插入失败的情况
            throw new RuntimeException("创建会话失败: " + e.getMessage(), e);
        }
    }

    @Override
    public List<SessionHistoryDao> getSessionList(Long userId) {
        // 参数校验
        ExceptionUtil.assertNotNull(userId, ErrorCode.PARAM_ERROR, "用户ID不能为空");

        // 查询指定用户的所有会话
        QueryWrapper<SessionHistoryDao> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).orderByDesc("update_time");

        return sessionHistoryMapper.selectList(queryWrapper);
    }

    @Override
    public SessionHistoryDao getSessionDetail(Long id, Long userId) {
        // 参数校验
        ExceptionUtil.assertNotNull(id, ErrorCode.PARAM_ERROR, "会话ID不能为空");
        ExceptionUtil.assertNotNull(userId, ErrorCode.PARAM_ERROR, "用户ID不能为空");

        // 查询会话详情
        QueryWrapper<SessionHistoryDao> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id).eq("user_id", userId);

        SessionHistoryDao sessionHistory = sessionHistoryMapper.selectOne(queryWrapper);
        ExceptionUtil.assertNotNull(sessionHistory, ErrorCode.SESSION_NOT_EXIST, "会话不存在");

        return sessionHistory;
    }

    @Override
    public SessionHistoryDao getSessionDetailWithMessages(Long id, Long userId) {
        // 参数校验
        ExceptionUtil.assertNotNull(id, ErrorCode.PARAM_ERROR, "会话ID不能为空");
        ExceptionUtil.assertNotNull(userId, ErrorCode.PARAM_ERROR, "用户ID不能为空");

        // 1. 查询会话基本信息
        SessionHistoryDao sessionHistory = getSessionDetail(id, userId);
        ExceptionUtil.assertNotNull(sessionHistory, ErrorCode.SESSION_NOT_EXIST, "会话不存在或无权访问");

        // 2. 查询会话的消息记录
        QueryWrapper<ChatMessageDao> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chat_history_id", id)
                .orderByAsc("serial_number"); // 按序列号升序排序
        List<ChatMessageDao> chatMessages = chatMessageMapper.selectList(queryWrapper);

        // 3. 将消息转换为DTO格式
        List<ChatMessageDto> messageDtos = chatMessages.stream()
                .map(message -> {
                    // 解析消息内容JSON
                    try {
                        JSONObject contentObj = JSON.parseObject(message.getContent());
                        String text = contentObj.getString("text");
                        String user = contentObj.getString("user");
                        Boolean isInterrupted = contentObj.getBoolean("isInterrupted");

                        // 创建DTO
                        ChatMessageDto dto = new ChatMessageDto();
                        dto.setValue(text);
                        dto.setUser(user);
                        dto.setTime(message.getCreateTime().toString());
                        dto.setIsInterrupted(isInterrupted);
                        dto.setParagraph(contentObj.getBoolean("paragraph"));
                        dto.setDefinite(contentObj.getBoolean("definite"));

                        return dto;
                    } catch (Exception e) {
                        // 日志记录解析异常
                        e.printStackTrace();
                        return null;
                    }
                })
                .filter(Objects::nonNull) // 过滤掉解析失败的消息
                .collect(Collectors.toList());

        // 4. 设置消息列表到会话对象
        sessionHistory.setMessages(messageDtos);

        return sessionHistory;
    }

    @Override
    @Transactional
    public boolean deleteSession(Long id, Long userId) {
        // 参数校验
        ExceptionUtil.assertNotNull(id, ErrorCode.PARAM_ERROR, "会话ID不能为空");
        ExceptionUtil.assertNotNull(userId, ErrorCode.PARAM_ERROR, "用户ID不能为空");

        // 先查询会话是否存在且属于该用户
        QueryWrapper<SessionHistoryDao> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id).eq("user_id", userId);

        SessionHistoryDao sessionHistory = sessionHistoryMapper.selectOne(queryWrapper);
        ExceptionUtil.assertNotNull(sessionHistory, ErrorCode.SESSION_NOT_EXIST, "会话不存在或无权删除");

        // 删除会话
        int result = sessionHistoryMapper.deleteById(id);
        return result > 0;
    }

    @Override
    @Transactional
    public SessionHistoryDao updateSession(SessionHistoryDao sessionHistory) {
        // 参数校验
        ExceptionUtil.assertNotNull(sessionHistory, ErrorCode.PARAM_ERROR, "会话不能为空");
        ExceptionUtil.assertNotNull(sessionHistory.getId(), ErrorCode.PARAM_ERROR, "会话ID不能为空");
        ExceptionUtil.assertNotNull(sessionHistory.getUserId(), ErrorCode.PARAM_ERROR, "用户ID不能为空");

        // 先查询会话是否存在且属于该用户
        SessionHistoryDao existingSession = sessionHistoryMapper.selectById(sessionHistory.getId());
        ExceptionUtil.assertNotNull(existingSession, ErrorCode.SESSION_NOT_EXIST, "会话不存在");

        // 确保用户只能更新自己的会话
        ExceptionUtil.assertTrue(
                existingSession.getUserId().equals(sessionHistory.getUserId()),
                ErrorCode.FORBIDDEN,
                "无权限修改此会话"
        );

        // 更新时间
        sessionHistory.setUpdateTime(new Date());

        // 更新会话
        sessionHistoryMapper.updateById(sessionHistory);

        return sessionHistory;
    }

    @Transactional
    public boolean addMessage(MessageRequest messageRequest, UserDao userId) {
        // 参数校验
        ExceptionUtil.assertNotNull(messageRequest, ErrorCode.PARAM_ERROR, "消息请求不能为空");
        ExceptionUtil.assertNotNull(messageRequest.getSessionId(), ErrorCode.PARAM_ERROR, "会话ID不能为空");
        ExceptionUtil.assertNotNull(messageRequest.getUser(), ErrorCode.PARAM_ERROR, "用户标识不能为空");

        // 查询会话是否存在，并且属于当前用户
        SessionHistoryDao sessionHistory = sessionHistoryMapper.selectById(messageRequest.getSessionId());
        ExceptionUtil.assertNotNull(sessionHistory, ErrorCode.SESSION_NOT_EXIST, "会话不存在");

        // 更新会话的更新时间
        sessionHistory.setUpdateTime(new Date());
        sessionHistoryMapper.updateById(sessionHistory);

        // 查询当前会话最大的序列号
        QueryWrapper<ChatMessageDao> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chat_history_id", messageRequest.getSessionId())
                .orderByDesc("serial_number")
                .last("LIMIT 1");
        ChatMessageDao lastMessage = chatMessageMapper.selectOne(queryWrapper);
        long serialNumber = 1;
        if (lastMessage != null) {
            serialNumber = lastMessage.getSerialNumber() + 1;
        }

        // 创建消息内容MAP
        Map<String, Object> contentMap = new HashMap<>();


        // 创建新消息记录
        ChatMessageDao chatMessage = new ChatMessageDao();
        chatMessage.setChatHistoryId(messageRequest.getSessionId());


         chatMessage.setContent(messageRequest.getText());

        chatMessage.setSerialNumber(serialNumber);

        // 设置消息角色
        if ((userId.getId() + "_" + userId.getUsername()).equals(messageRequest.getUser())) {
            chatMessage.setRole((userId.getId() + "_" + userId.getUsername()));

        } else {
            chatMessage.setRole("🐙杨");

        }
        chatMessage.setCreateTime(new Date());
        // 保存消息
        int result = chatMessageMapper.insert(chatMessage);
        return result > 0;
    }

    @Override
    public List<String> getMessageHistoryForVoiceChat(Long userId, String roomId) {
        // 参数校验
        ExceptionUtil.assertNotNull(userId, ErrorCode.PARAM_ERROR, "用户ID不能为空");
        ExceptionUtil.assertNotNull(roomId, ErrorCode.PARAM_ERROR, "房间ID不能为空");

        // 1. 根据用户ID和房间ID查找会话
        QueryWrapper<SessionHistoryDao> sessionQueryWrapper = new QueryWrapper<>();
        sessionQueryWrapper.eq("user_id", userId)
                .eq("room_id", roomId);
        SessionHistoryDao sessionHistory = sessionHistoryMapper.selectOne(sessionQueryWrapper);

        // 如果找不到会话，返回空列表
        if (sessionHistory == null) {
            return new ArrayList<>();
        }

        // 2. 查询该会话中的消息记录
        QueryWrapper<ChatMessageDao> messageQueryWrapper = new QueryWrapper<>();
        messageQueryWrapper.eq("chat_history_id", sessionHistory.getId())
                .orderByAsc("serial_number"); // 按消息顺序排序
        List<ChatMessageDao> chatMessages = chatMessageMapper.selectList(messageQueryWrapper);

        // 如果没有消息，返回空列表
        if (chatMessages == null || chatMessages.isEmpty()) {
            return new ArrayList<>();
        }

        // 3. 将消息转换为LLM需要的格式 (user: "内容", assistant: "内容")
        List<String> formattedMessages = new ArrayList<>();
        for (ChatMessageDao message : chatMessages) {
            try {
                // 解析消息内容JSON
                JSONObject contentObj = JSON.parseObject(message.getContent());
                String text = contentObj.getString("text");
                String user = contentObj.getString("user");

                // 根据消息发送者角色格式化
                String formattedMessage;
                if ("user".equals(user)) {
                    formattedMessage = "user:\"" + text + "\"";
                } else {
                    formattedMessage = "assistant:\"" + text + "\"";
                }

                formattedMessages.add(formattedMessage);
            } catch (Exception e) {
                // 解析失败的消息跳过
                e.printStackTrace();
            }
        }

        // 4. 只返回最近的一组对话（最多5组问答，即10条消息）
         return formattedMessages;
    }
}
